package com.fruit.service.pay.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.fruit.constants.BillConstant;
import com.fruit.constants.GoodsContant;
import com.fruit.constants.OrderConstant;
import com.fruit.constants.PayConstant;
import com.fruit.mapper.lightpay.LightPayMapper;
import com.fruit.mapper.pay.PayMapper;
import com.fruit.pojo.goods.GoodsSpec;
import com.fruit.pojo.lightpay.LightPayCashier;
import com.fruit.pojo.order.Order;
import com.fruit.pojo.order.OrderGoods;
import com.fruit.pojo.pay.BillDetail;
import com.fruit.pojo.pay.PayInfo;
import com.fruit.pojo.pay.TransactionFlow;
import com.fruit.service.order.OrderManager;
import com.fruit.service.pay.PayManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.DataUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

@Service("payService")
public class PayService implements PayManager{

	
	@Autowired
	private PayMapper payMapper;
	
	@Autowired
	private OrderManager orderService;
	
	@Autowired
	private LightPayMapper lightPayMapper;
	
	@Override
	public Map<String, Object> saveSubmitOrder(PayInfo pi) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		//判断商品是否存在
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", pi.getGoodsSpecId());
		GoodsSpec goodsSpec = payMapper.getGoodsSpecById(params);
		if(goodsSpec == null || GoodsContant.State.DOWN.equals(goodsSpec.getState())){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "商品已下架"));
			return resMap;
		}
		//判断金额
		goodsSpec.setNum(pi.getNum());
		BigDecimal totalPrice = DataUtil.mul(2, goodsSpec.getPrice(),goodsSpec.getNum());
		
		if(totalPrice.compareTo(pi.getTotalPrice()) !=0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "金额错误"));
			return resMap;
		}
		if( pi.getNum() > goodsSpec.getMaxShopNum() || pi.getNum()<goodsSpec.getMinShopNum()){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "购买数量有误"));
			return resMap;
		}
		
		//初始化数据
		pi.getGsList().add(goodsSpec);
		pi.setRemark(goodsSpec.getTitle());
		pi.setPayPrice(pi.getTotalPrice());
		
		//减去库存
		int num = payMapper.updateGoodsSpecStockNum(goodsSpec);
		if(num == 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "goods_error", "库存不足!", null, ResultInfo.ROLLBACK));
			return resMap;
		}
		
		//插入账单、交易流水、订单记录
		resMap = saveOrder(pi);

		return resMap;
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
		}finally{
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.ROLLBACK.equals(ri.getIsRollBack())){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}

	public Map<String, Object> saveOrder(PayInfo pi){
		Map<String, Object> resMap = new HashMap<String, Object>();
		/*String curTime = DateUtil.getTime();
		BillDetail bd = new BillDetail();
		bd.setUserId(pi.getUserId());
		bd.setType(BillConstant.Type.consume.getValue());
		bd.setMoney(pi.getTotalPrice());
		bd.setMoneyState(BillConstant.MoneyState.go.getValue());
		bd.setState(BillConstant.State.handel.getValue());
		bd.setCreateTime(curTime);
		bd.setRemark(pi.getRemark());
		payMapper.saveBillDetail(bd);
		TransactionFlow tf = new TransactionFlow();
		tf.setUserId(pi.getUserId());
		tf.setTotalPrice(pi.getTotalPrice());
		tf.setPayPrice(pi.getPayPrice());
		tf.setPriceState(BillConstant.MoneyState.go.getValue());
		tf.setRemark(pi.getRemark());
		tf.setState(PayConstant.State.notpay.getValue());
		tf.setType(BillConstant.Type.consume.getValue());
		tf.setCreateTime(curTime);
		payMapper.saveTransactionFlow(tf);
		tf.setCode(CustomUtil.orderCode(3, tf.getId(), pi.getUserId()));
		int num = payMapper.updateTransactionFlowCode(tf);
		if(num != 1){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!", null, ResultInfo.ROLLBACK));
			return resMap;
		}
		//插入订单
		Order order = new Order();
		order.setTransactionId(tf.getId());
		order.setUserId(pi.getUserId());
		order.setType(OrderConstant.Type.goods.getValue());
		order.setState(OrderConstant.State.notpay.getValue());
		order.setTotalPrice(pi.getTotalPrice());
		order.setRealPrice(pi.getTotalPrice());
		order.setCreateTime(curTime);
		order.setUpdateTime(curTime);
		payMapper.saveOrder(order);
		order.setCode(CustomUtil.orderCode(3, order.getId(), pi.getUserId()));
		num = payMapper.updateOrderCode(order);
		if(num != 1){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!", null, ResultInfo.ROLLBACK));
			return resMap;
		}
		
		//插入订单商品
		for(GoodsSpec gs : pi.getGsList()){
			OrderGoods og = new OrderGoods();
			og.setOrderId(order.getId());
			og.setUserId(pi.getUserId());
			og.setGoodsId(gs.getGoodsId());
			og.setGoodsSpecId(gs.getId());
			og.setGoodsSpecCode(gs.getCode());
			og.setClassId(gs.getClassId());
			og.setTitle(gs.getTitle());
			og.setSubTitle(gs.getSubTitle());
			og.setGoodsThumb(gs.getThumb());
			og.setBidPrice(gs.getBidPrice());
			og.setPrice(gs.getPrice());
			og.setNumber(gs.getNum());
			og.setUnit(gs.getUnit());
			og.setUnitDesc(gs.getUnitDesc());
			og.setSpec(gs.getSpec());
			og.setFruitTreeState(gs.getFruitTreeState());
			og.setHarvestTime(gs.getHarvestTime());
			num = payMapper.saveOrderGoods(og);
			if(num != 1){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!", null, ResultInfo.ROLLBACK));
				return resMap;
			}
		}
		resMap.put("transactionCode", tf.getCode());
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
		//加入订单取消队列
*/		return resMap;
	}

	@Override
	public Map<String, Object> updateTransaction(long lpcId, String transactionCode) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try{
		//判断交易流水状态
	    TransactionFlow tf = payMapper.getTransactionFlow(transactionCode);
	    if(tf != null){
	    	if(PayConstant.State.cancel.equals(tf.getState()) 
	    			||PayConstant.State.pay.equals(tf.getState())){
	    		//退款流程
	    	}else if(PayConstant.State.notpay.equals(tf.getState())){
	    		//判断业务类型
	    		
	    		if(PayConstant.Type.consume.equals(tf.getType())){
	    			tf.setState(PayConstant.State.pay.getValue());
	    			int num = payMapper.updateTransactionFlowState(tf);
	    			if(num == 1){
	    				num = orderService.updateOrderState(tf.getId());
	    			}
	    			if(num == 1){
	    				LightPayCashier lpc = lightPayMapper.getLightpayCashierById(lpcId);
	    				lpc.setResultHandelState(PayConstant.RHandelState.yes.getValue());
	    				num = lightPayMapper.updateLightpayRhState(lpc);
	    			}
	    			if(num == 0){
	    				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "处理失败!", null, ResultInfo.ROLLBACK));
	    				return resMap;
	    			}
	    			
	    		}
	    	}
	    	
	    }
	    resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "处理成功"));
		return resMap;
	    
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
		}finally{
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.ROLLBACK.equals(ri.getIsRollBack())){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}

	@Override
	public TransactionFlow getTransactionFlow(String transactionCode) {
		return payMapper.getTransactionFlow(transactionCode);
	}
	
	
}
